package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 订单信息分页查询
     *
     * @param page
     * @param pageSize
     * @param
     * @return
     */
    @GetMapping("/userPage")
    public R page(int page, int pageSize) {
        //分页构造器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();

        qw.orderByDesc(Orders::getCheckoutTime);
//        //添加查询条件，根据name进行like模糊查询
//        queryWrapper.like(orders != null,Orders::,name);
        //添加排序条件，根据更新时间降序排列
//        queryWrapper.orderByDesc(Orders::getUpdateTime);

        orderService.page(pageInfo, qw);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Orders> records = pageInfo.getRecords();
// 拉姆达表达式
        List<OrdersDto> list = records.stream().map((item) -> {


            OrdersDto ordersDto = new OrdersDto();
            //对象拷贝
            BeanUtils.copyProperties(item, ordersDto);
            //分类id
            Long ordersid = item.getId();
            //根据分类id查询分类对象

            LambdaQueryWrapper<OrderDetail> qww = new LambdaQueryWrapper<>();

            qww.eq(OrderDetail::getOrderId, ordersid);
            //OrdersDto中的ordersdetail是list集合 所以调用list方法存入该list
            List<OrderDetail> list1 = orderDetailService.list(qww);

            ordersDto.setOrderDetails(list1);


            return ordersDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }
}